package kr.co.casually.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.location.Location;

import com.google.android.maps.GeoPoint;

public class MapUtil {

	public String getDaumLatLng(String x, String y) {
		String latlng = "";
		String key="6cea6ff57735ed8e1041afa7f035cbe5b625cf0f"; // 다음 local api 키
		
		String html = "http://apis.daum.net/local/geo/transcoord?apikey="+key+"&x="
				+ x + "&y=" + y + "&fromCoord=KTM&toCoord=WGS84&output=xml";
		try {

			URL url = new URL(html);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"utf-8"));

					XmlPullParserFactory factory = XmlPullParserFactory
							.newInstance();
					factory.setNamespaceAware(true);
					XmlPullParser xpp = factory.newPullParser();
					xpp.setInput(br);
					int eventType = xpp.getEventType();

					String mapx = "";
					String mapy = "";
					while (eventType != XmlPullParser.END_DOCUMENT) {

						if (eventType == XmlPullParser.START_TAG) {

							mapx = xpp.getAttributeValue(0);
							mapy = xpp.getAttributeValue(1);

						}
						
						
						latlng = mapx + "," + mapy;
						eventType = xpp.next();
					}

					br.close();
				}

			}
			conn.disconnect();

		} catch (Exception e) {
		}

		return latlng;

	}

	public GeoPoint getGeoPoint(Location location) {
		if (location == null) {
			return null;
		}
		Double lat = location.getLatitude() * 1E6;
		Double lng = location.getLongitude() * 1E6;
		return new GeoPoint(lat.intValue(), lng.intValue());
	}

	public Double getGoogleLat(String address, String doc) {
		Double lat = 0.0;
		String url = "http://maps.google.com/maps/api/geocode/" + doc
				+ "?address=" + address + "&sensor=false&region=es";
		if (doc.equals("json")) {
			String jString = getResultConn(url);
			JSONObject jObject;
			try {
				jObject = new JSONObject(jString);
				String status = jObject.getString("status");
				if (status.equals("OK")) {
					JSONArray resultArr = new JSONArray(jObject
							.getString("results"));
					JSONObject geometryObject = resultArr.getJSONObject(0)
							.getJSONObject("geometry");
					JSONObject locationObject = geometryObject
							.getJSONObject("location");
					lat = locationObject.getDouble("lat");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {

		}

		return lat;

	}

	public Double getGooglelng(String address, String doc) {
		Double lng = 0.0;
		String url = "http://maps.google.com/maps/api/geocode/" + doc
				+ "?address=" + address + "&sensor=false&region=es";

		if (doc.equals("json")) {
			String jString = getResultConn(url);
			JSONObject jObject;
			try {
				jObject = new JSONObject(jString);
				String status = jObject.getString("status");
				if (status.equals("OK")) {
					JSONArray resultArr = new JSONArray(jObject
							.getString("results"));

					JSONObject geometryObject = resultArr.getJSONObject(0)
							.getJSONObject("geometry");
					JSONObject locationObject = geometryObject
							.getJSONObject("location");
					lng = locationObject.getDouble("lng");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {

		}

		return lng;

	}

	public double getDistanceTo(Location findLoc, Location myLoc) {
		double distance = 0.0;

		Location bLocation = new Location("reverseGeocoded");
		bLocation.setLatitude(findLoc.getLatitude()); // Value = 3.294391E7
		bLocation.setLongitude(findLoc.getLongitude()); // Value = -9.6564615E7

		Location aLocation = new Location("reverseGeocoded");
		aLocation.setLatitude(myLoc.getLatitude()); // Value = 3.2946164E7
		aLocation.setLongitude(myLoc.getLongitude()); // Value = -9.6505141E7
		aLocation.set(aLocation); // Don't think I need this
		bLocation.set(bLocation); // Don't think I need this either

		distance = aLocation.distanceTo(bLocation) / 1000; // Value =


		return distance;
	}

	public String getResultConn(String html) {
		String result = "";

		try {

			URL url = new URL(html);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);
				StringBuilder sb = new StringBuilder();
				String line;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"utf-8"));
					while ((line = br.readLine()) != null) {
						sb.append(line).append("\n");
					}
					result = sb.toString();

					br.close();
				}
				conn.disconnect();
			}

		} catch (Exception e) {
		}

		return result;

	}

	public String getResultHttp(String url) {
		String result = "";
		final HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, "UTF-8");
		HttpProtocolParams.setUserAgent(params, "android");

		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 10000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);

		DefaultHttpClient httpclient = new DefaultHttpClient(params);
		HttpGet httpget = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				result = convertStreamToString(instream);
				instream.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
